import pymysql

DB = None


def get_connection():
    global DB
    # 三元表达式只用于取值，不用于赋值，打错特错
    # return DB if DB is not None else DB = pymysql.connect(host='localhsot', user='root', password='123456',
    #                                                       database='cdm',
    #                                                       port=3306)
    if DB is None:
        try:
            DB = pymysql.connect(host='localhost', user='root', password='123456',
                                 database='cdm',
                                 port=3306)
            print('连接数据库成功')
            return DB
        except Exception as e:
            print(f'连接数据库失败,{e}')
            return None

    else:
        return DB


def insert_data_to_hub(records: list,table_name):
    """
    :param records:  生成的sql的 list语句
    :param table_name: 往哪张表写入数据
    :return:
    """
    db = get_connection()
    # 创建一个游标对象
    cursor = db.cursor()
    # 使用execute方法
    count = 0
    for i in range(len(records)):
        try:
            cursor.execute(records[i])
            # 提交到数据库执行
            db.commit()
            count += 1
        except Exception as e:
            # 如果发生错误则回滚
            db.rollback()

    print(f'总共往{table_name}里写入了{count}条数据')


if __name__ == '__main__':
    # insert_data_to_hub()
    db = get_connection()
    print(db)
